import Api from '../../utils/httpImpl';
const api = new Api();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "毛泽东思想是取得新民主主义革命胜利、进行社会主义建设的思想指导。在全国解放战争时期和新中国建立以后，毛泽东思想继续得到发展，集中体现在",
    choose: ["人民民主专政理论", "正确处理人民内部矛盾的理论", "社会主义改造理论", "提出了马列主义基本原理同中国革命和建设具体实际的“第二次结合”"],
    digit: [], //正确答案
    type: 0, //0代表单选题，1代表多选题，2是判断题
    index: 2,
    total: 3,
    answer: [], //回答答案
    isSelected: [false, false, false, false],
    analysis: "半殖民地半封建社会的近代中国存在着两对矛盾，一是封建主义与人民大众的矛盾，二是帝国主义和中华民族的矛盾，其中最主要的矛盾是帝国主义和中化民族的矛盾，A正确。",
    isChosen: false,
    isConfirmed: false,
    chapterId: 0, //章节id
    titleList: [], //题目列表
    titleJson: {}, //题目内容
    currentIndex: 1, //当前题目
    isRandom: 'no', //是否是随机
    optionsList: [], //选项
    titleAnswerCount: 0
  },
  onLoad(options) {
    if (options.id) {
      this.setData({
        chapterId: options.id
      });
    }
    //随机刷题
    if (options.isRandom) {
      this.setData({
        isRandom: options.isRandom
      });
      this.getRandomTitle();
    }else if(options.item){ //错题答题
      let title = JSON.parse(options.item);
      this.setData({
        titleJson: title,
        titleList: [{
          title_id: title.title_id
        }],
        total: 1,
        optionsList: title.titleCont.split(','),
        titleAnswerCount: title.titleAnswer.split(',').length
      })
    }else {
      this.getData();
    }
  },
  //答题
  choose: function (e) {
    //已经回答
    if (this.data.isConfirmed) {
      return;
    }
    let index1 = e.currentTarget.dataset.index;
    let isSelected = this.data.isSelected
    let isChosen = false;
    let answer = [];
    let option = ['A', 'B', 'C', 'D'];
    let select = this.data.isSelected[index1]
    if (this.data.titleAnswerCount > 1) {
      this.data.isSelected[index1] = !select
    } else {
      if (!select) {
        for (let index = 0; index < this.data.isSelected.length; index++)
          this.data.isSelected[index] = false
        this.data.isSelected[index1] = true
      }
    }
    for (let index = 0; index < this.data.isSelected.length; index++) {
      if (this.data.isSelected[index]) {
        answer.push(option[index]);
      }
    }
    this.setData({
      isSelected: this.data.isSelected,
      answer: answer
    });
  },
  //提交答案
  async tapConfirm() {
    if (this.data.answer.length > 0) {
      //提交后台
      let _json = {
        title_id: this.data.titleList[this.data.currentIndex - 1].title_id,
        user_id: wx.getStorageSync('userId'),
        answer: this.data.answer.join(','),
        user_note: ''
      };
      const result = await api.setAnswer(_json);
      console.log(result.data);
      let answers = this.data.answer.sort(); //回答答案
      let realAn = this.data.titleJson.titleAnswer.split(','); //题目答案
      realAn = realAn.sort();
      if (answers.join(',') === realAn.join(',')) {
        wx.showToast({
          title: '回答正确',
        });
        //删除错题
        this.delWrong();
      } else {
        wx.showToast({
          title: '回答错误，已加入错题库',
          icon: 'none'
        });
        //加入错题
        this.setWrong();
      }
      this.setData({
        isConfirmed: true
      });
    } else {
      wx.showToast({
        title: '请选择答案后再确定',
        icon: 'none'
      });
    }
  },
  //获取题目
  async getData() {
    let _json = {
      chapters_id: this.data.chapterId
    };
    const result = await api.getTitleById(_json);
    //题目数组
    let titleIdList = result.titles;
    if (titleIdList instanceof Array && titleIdList.length) {
      //
      const result2 = await api.getTitleDetail({
        title_id: titleIdList[0].title_id
      });
      console.log(result2.titleCont);
      this.setData({
        titleJson: result2,
        titleList: titleIdList,
        total: titleIdList.length,
        optionsList: result2.titleCont.split(','),
        titleAnswerCount: result2.titleAnswer.split(',').length
      });
    }
  },
  //再来随机一题
  nextRandomFn() {
    //数据清空
    for (let index = 0; index < this.data.isSelected.length; index++) {
      this.data.isSelected[index] = false;
    }
    this.setData({
      answer: [],
      optionsList: [],
      isConfirmed: false,
      isSelected: this.data.isSelected,
    });
    this.getRandomTitle();
  },
  //获取随机题目
  async getRandomTitle(data) {
    const result = await api.getRandomTitle(data);
    this.setData({
      titleJson: result,
      total: 1,
      titleList: [{
        title_id: result.title_id
      }],
      optionsList: result.titleCont.split(','),
      titleAnswerCount: result.titleAnswer.split(',').length
    });
  },
  //上一题
  prevFn() {
    for (let index = 0; index < this.data.isSelected.length; index++) {
      this.data.isSelected[index] = false;
    }
    this.setData({
      currentIndex: this.data.currentIndex - 1,
      answer: [],
      optionsList: [],
      isConfirmed: false,
      isSelected: this.data.isSelected,
    });
    this.getTitle();
  },
  //下一题
  nextFn() {
    for (let index = 0; index < this.data.isSelected.length; index++)
      this.data.isSelected[index] = false
    this.setData({
      isSelected: this.data.isSelected,
      answer: [],
      optionsList: [],
      isConfirmed: false
    })
    if (this.data.currentIndex < this.data.titleList.length) {
      this.setData({
        currentIndex: this.data.currentIndex + 1
      });
      this.getTitle();
    } else {
      wx.showToast({
        title: '答完了',
        icon: 'none'
      });
    }
  },
  //获取题目内容
  async getTitle() {
    const result2 = await api.getTitleDetail({
      title_id: this.data.titleList[this.data.currentIndex - 1].title_id
    });
    this.setData({
      titleJson: result2,
      optionsList: result2.titleCont.split(','),
      titleAnswerCount: result2.titleAnswer.split(',').length
    });
  },
  //设置错题
  setWrong() {
    let localData = wx.getStorageSync('wrong') || '';
    if (localData) {
      let ary = localData;
      let ary2 = [];
      let titleId = this.data.titleList[this.data.currentIndex - 1].title_id;
      console.log(titleId);
      for (let iterator of ary) {
        if (iterator.userId == wx.getStorageSync('userId')) {
          ary2 = iterator.content;
          if(ary2.length){
            let isHave = 'no';
            for (const item of ary2) {
              if (item.title_id == titleId) {
                isHave = 'yes';
              }
            }
            if(isHave == 'no') {
              ary2.push(this.data.titleJson);
              iterator.content = ary2;
            }
          }else {
            ary2.push(this.data.titleJson);
            iterator.content = ary2;
          }
        }
      }
      wx.setStorageSync('wrong', ary);
    } else {
      let ary = [];
      ary.push(this.data.titleJson);
      let wrong = {
        userId: wx.getStorageSync('userId'),
        content: ary
      };
      let ary2 = [];
      ary2.push(wrong);
      wx.setStorageSync('wrong', ary2);
    }
  },
  //删除错题
  delWrong() {
    let localData = wx.getStorageSync('wrong') || '';
    if (localData) {
      let ary = localData;
      let ary2 = [];
      let titleId = this.data.titleList[this.data.currentIndex - 1].title_id;
      for (let iterator of ary) {
        if (iterator.userId == wx.getStorageSync('userId')) {
          ary2 = iterator.content;
          for (let i = 0; i < ary2.length; i++) {
            //已存在，删除错题
            if (ary2[i].title_id == titleId) {
              ary2.splice(i, 1);
              iterator.content = ary2;
            }
          }
        }
      }
      wx.setStorageSync('wrong', ary);
    } else {
      return;
    }
  }
})